<template>
  <div class="p-2">
    <!-- 添加或修改任务对话框 -->
    <el-form ref="taskFormRef" :model="form" :rules="rules" label-width="140px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model="form.taskName" placeholder="请输入任务名称" :disabled="dialog.title === '修改任务'" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务类型" prop="taskTypeId">
            <el-select v-model="form.taskTypeId" :disabled="dialog.title === '修改任务'" placeholder="请选择任务类型" clearable>
              <el-option v-for="item in taskOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item v-if="xtId === form.taskTypeId" label="协调人" prop="collaborators">
            <task-user v-model="form.collaborators"></task-user>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="处理人" prop="handlerUserName">
            <user-input v-model="form.handlerUserId" v-model:name="form.handlerUserName" :disabled="dialog.title === '修改任务'"></user-input>
          </el-form-item>
        </el-col>
        <el-col v-if="dialog.title === '修改任务'" :span="12">
          <el-form-item label="任务状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择">
              <el-option v-for="dict in task_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="任务总绩效分" prop="taskName">-->
        <!--              <el-input v-model="form.originalScore" placeholder="请输入任务总绩效分" :disabled="dialog.title === '修改任务'" />-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
      </el-row>
      <el-form-item label="任务内容">
        <editor v-model="form.content" />
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="预计开始时间" prop="expectedStartTime">
            <el-date-picker
              v-model="form.expectedStartTime"
              clearable
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择预计开始时间"
              :disabled="dialog.title === '修改任务'"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预计结束时间" prop="expectedEndTime">
            <el-date-picker
              v-model="form.expectedEndTime"
              clearable
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择预计结束时间"
              :disabled="dialog.title === '修改任务'"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="附件（多个）" prop="enclosure">
        <file-upload v-model="form.enclosure" />
        <el-button type="danger" round @click="downLoadErrorFile">下载错误文件</el-button>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
      </el-form-item>
    </el-form>
    <template>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </div>
</template>

<script setup name="Task" lang="ts">
import { pageTask, getTask, delTask, addTask, updateTask, turn, downLoadRestockingTemplate } from '@/api/task/task';
import { TaskVO, TaskQuery, TaskForm, Collaborator } from '@/api/task/task/types';
import { listTaskType } from '@/api/task/taskType';
import PersonSelect from '@/views/target/person/PersonSelect.vue';
import useUserStore from '@/store/modules/user';
import { globalHeaders } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { task_status, user_type, review_status } = toRefs<any>(proxy?.useDict('task_status', 'user_type', 'review_status'));
const taskList = ref<TaskVO[]>([]);
const taskOptions = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);

const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const taskFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const isVisible = ref(false);
const uploadRef = ref<ElUploadInstance>();

/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/oa/task/importData'
});

const initFormData: any = {
  taskId: undefined,
  taskName: undefined,
  taskTypeId: undefined,
  content: undefined,
  fileName: undefined,
  expectedStartTime: undefined,
  expectedEndTime: undefined,
  actualStartTime: undefined,
  actualEndTime: undefined,
  // score: undefined,
  // originalScore: undefined,
  handlerUserId: undefined,
  userType: undefined,
  status: undefined,
  remark: undefined,
  collaborators: []
};
const validateEndTime = (rule, value, callback) => {
  if (form.value.expectedEndTime && form.value.expectedStartTime && form.value.expectedEndTime < form.value.expectedStartTime) {
    callback(new Error('预计结束时间不能小于预计开始时间'));
  } else {
    callback();
  }
};
const data = reactive<PageData<TaskForm, TaskQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskName: undefined,
    taskTypeId: undefined,
    content: undefined,
    expectedStartTime: undefined,
    expectedEndTime: undefined,
    actualStartTime: undefined,
    actualEndTime: undefined,
    // score: undefined,
    handlerUserId: undefined,
    userType: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    taskId: [{ required: false, message: '不能为空', trigger: 'blur' }],
    taskName: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
    taskTypeId: [{ required: true, message: '任务类型不能为空', trigger: 'change' }],
    content: [{ required: true, message: '任务内容不能为空', trigger: 'blur' }],
    actualStartTime: [{ required: true, message: '实际开始时间不能为空', trigger: 'blur' }],
    actualEndTime: [{ required: true, message: '实际结束时间不能为空', trigger: 'blur' }],
    // score: [{ required: true, message: '绩效分不能为空', trigger: 'blur' }],
    handlerUserId: [{ required: true, message: '处理人不能为空', trigger: 'blur' }],
    userType: [{ required: true, message: '用户类型不能为空', trigger: 'change' }],
    status: [{ required: true, message: '任务状态不能为空', trigger: 'change' }],
    remark: [{ required: false, message: '备注不能为空', trigger: 'blur' }],
    expectedStartTime: [{ required: true, message: '预计开始时间不能为空', trigger: 'blur' }],
    expectedEndTime: [
      { required: true, message: '预计结束时间不能为空', trigger: 'blur' },
      { validator: validateEndTime, trigger: 'blur' }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

const xtId = computed(() => {
  return taskOptions.value.find((item) => item.name === '协调任务')?.id;
});

/** 查询任务列表 */
const getList = async () => {
  loading.value = true;
  const res = await pageTask(queryParams.value);
  taskList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 查询任务列表 */
const getTaskList = async () => {
  loading.value = true;
  const res = await listTaskType();
  taskOptions.value = res.rows;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  taskFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TaskVO[]) => {
  ids.value = selection.map((item) => item.taskId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加任务';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TaskVO) => {
  reset();
  const _taskId = row?.taskId || ids.value[0];
  const res = await getTask(_taskId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改任务';
};

/** 查看按钮操作 */
// const handleView = (row?: TaskVO) => {
//   proxy.$tab.closePage(proxy.$route);
//   proxy.$router.push({
//     path: `/workflow/task/index`,
//     query: {
//       processInstanceId: row.processInstanceId,
//       type: 'view'
//     }
//   });
// };
const userStore = useUserStore();

const isNotTurn = (status: number) => {
  return status == 2 || status == 4;
};

const changeTaskStatus = async (taskId: string, state: string) => {
  loading.value = true;
  reset();
  const res = await turn({ taskId, status: state }).finally(() => (loading.value = false));
  if (res.code == 200) {
    proxy?.$modal.msgSuccess('操作成功');
    await getList();
  } else {
    proxy?.$modal.msgError(res.msg);
  }
  loading.value = false;
};

/** 提交按钮 */
const submitForm = () => {
  taskFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;

      if (form.value.collaborators) {
        for (const coordinator of form.value.collaborators) {
          const startTime = new Date(coordinator.expectedStartTime);
          const endTime = new Date(coordinator.expectedEndTime);

          if (endTime < startTime) {
            proxy?.$modal.msgError('协调人' + coordinator.handlerUserName + '预计结束时间不能小于预计开始时间');
            buttonLoading.value = false;
            return;
          }
        }
      }

      if (form.value.taskId) {
        await updateTask(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTask(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TaskVO) => {
  const _taskIds = row?.taskId || ids.value;
  await proxy?.$modal.confirm('是否确认删除任务编号为"' + _taskIds + '"的数据项？').finally(() => (loading.value = false));
  await delTask(_taskIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oa/task/export',
    {
      ...queryParams.value
    },
    `task_${new Date().getTime()}.xlsx`
  );
};

const handleDownLoadRestockingTemplate = async () => {
  proxy?.download(
    '/oa/task/downLoadRestockingTemplate',
    {
      ...queryParams.value
    },
    `补货计划模板_${new Date().getTime()}.xlsx`
  );
};

const downLoadErrorFile = async () => {
  proxy?.download(
    '/oa/task/downLoadErrorFile',
    {
      ...form.value
    },
    `错误信息模板_${new Date().getTime()}.xlsx`
  );
};

/** 下载模板操作 */
const downLoadImportTemplate = () => {
  proxy?.download('oa/task/downLoadImportTemplate', {}, `任务模板_${new Date().getTime()}.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '版本号导入';
  upload.open = true;
};

onMounted(() => {
  getList();
  getTaskList();
});
</script>

<style>
.editor {
  width: 100%;
}
</style>
